package com.example.baselib;

import com.example.baselib.utils.log.LogUtils;
import ohos.agp.components.*;
import ohos.agp.utils.Color;
import ohos.app.Context;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;

import java.io.InputStream;
import java.util.Optional;


/**
 * 自定义标题栏
 */
public class TitleLayout extends ComponentContainer {

    private boolean showBackLayout = true;
    private String text = "";
    private int textSize = 14;
    private Color textColor = Color.BLACK;
    private DirectionalLayout titleParent;
    private DependentLayout backLayout;
    private DependentLayout customRightLayout;
    private DirectionalLayout defaultLayout;
    private DependentLayout defaultRightLayout;
    private Text ttTitle;
    private Image iconImg;

    public TitleLayout(Context context) {
        this(context, null, null);
    }

    public TitleLayout(Context context, AttrSet attrSet) {
        this(context, attrSet, null);
    }

    public TitleLayout(Context context, AttrSet attrSet, String styleName) {
        super(context, attrSet, styleName);
        init(context, attrSet);
    }

    private void init(Context context, AttrSet attrSet) {
        titleParent = (DirectionalLayout) LayoutScatter.getInstance(context).parse(ResourceTable.Layout_title_layout, null, false);
        addComponent(titleParent);
        backLayout = findComponentFromId(ResourceTable.Id_title_back);
        customRightLayout = findComponentFromId(ResourceTable.Id_title_custom_layout);
        defaultLayout = findComponentFromId(ResourceTable.Id_title_default_layout);
        defaultRightLayout = findComponentFromId(ResourceTable.Id_title_default_right);
        iconImg = findComponentFromId(ResourceTable.Id_icon_back);

        ttTitle = findComponentFromId(ResourceTable.Id_tt_title);

        Optional<Attr> attrOptional = attrSet.getAttr("title_callback_show");
        //是否存在该属性
        if (attrOptional.isPresent()) {
            showBackLayout = attrOptional.get().getBoolValue();
        }
        isShowCallback(showBackLayout);

        attrOptional = attrSet.getAttr("title_text");
        if (attrOptional.isPresent()) {
            text = attrOptional.get().getStringValue();
            LogUtils.d("title_text = %s", text);
        }else {
            LogUtils.d("default text = %s", text);
        }
        setTitle(text);

        attrOptional = attrSet.getAttr("title_size");
        if (attrOptional.isPresent()) {
            textSize = attrOptional.get().getIntegerValue();
            LogUtils.d("title_size = %s", textSize);
        }else {
            LogUtils.d("default title size = %s", textSize);
        }
        setTitleSize(textSize);

        attrOptional = attrSet.getAttr("title_color");
        if (attrOptional.isPresent()) {
            textColor = attrOptional.get().getColorValue();
            LogUtils.d("title_color = %s", textColor.getValue());
        }else {
            LogUtils.d("default title color = %s", textColor.getValue());
        }
        setTitleColor(textColor);

    }


    /**
     * 设置标题文字
     */
    public TitleLayout setTitle(String character) {
        if (ttTitle != null
                && ttTitle.getVisibility() == VISIBLE
                && defaultLayout.getVisibility() == VISIBLE) {
            ttTitle.setText(character);
        }
        return this;
    }

    public TitleLayout setTitle(int resId) {
        if (ttTitle != null
                && ttTitle.getVisibility() == VISIBLE
                && defaultLayout.getVisibility() == VISIBLE) {
            ttTitle.setText(resId);
        }
        return this;
    }

    /**
     * 设置标题文字颜色
     */
    public TitleLayout setTitleColor(Color color) {
        if (ttTitle != null
                && ttTitle.getVisibility() == VISIBLE
                && defaultLayout.getVisibility() == VISIBLE) {
            ttTitle.setTextColor(color);
        }
        return this;
    }

    /**
     * 设置标题文字大小
     */
    public TitleLayout setTitleSize(int size) {
        if (ttTitle != null
                && ttTitle.getVisibility() == VISIBLE
                && defaultLayout.getVisibility() == VISIBLE) {
            ttTitle.setTextSize(size, Text.TextSizeType.FP);
        }
        return this;
    }

    /**
     * 设置返回图标
     */
    public TitleLayout setCallbackIcon(int resId) {
        try {
            InputStream resource = getResourceManager().getResource(resId);
            ImageSource.SourceOptions sourceOptions = new ImageSource.SourceOptions();
            sourceOptions.formatHint = "image/png";

            ImageSource imageSource = ImageSource.create(resource, sourceOptions);

            ImageSource.DecodingOptions options = new ImageSource.DecodingOptions();
            PixelMap pixelmap = imageSource.createPixelmap(options);
            return setCallbackIcon(pixelmap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return this;
    }

    /**
     * 设置返回图标
     */
    public TitleLayout setCallbackIcon(PixelMap pixelMap) {
        if (backLayout != null) {
            if (backLayout.getVisibility() != VISIBLE) {
                backLayout.setVisibility(VISIBLE);
            }
            Image iconImg = (Image) findComponentById(ResourceTable.Id_icon_back);
            if (iconImg == null) {
                return this;
            }
            if (iconImg.getVisibility() != VISIBLE) {
                iconImg.setVisibility(VISIBLE);
            }
            iconImg.setPixelMap(pixelMap);
        }
        return this;
    }


    /**
     * 设置返回按钮的状态
     */
    public TitleLayout isShowCallback(boolean bool) {
        this.showBackLayout = bool;
        setShowCallback(bool ? VISIBLE : INVISIBLE);
        return this;
    }

    /**
     * 设置返回按钮的状态
     */
    public TitleLayout setShowCallback(int visibility) {
        if (backLayout != null) {
            backLayout.setVisibility(visibility);
        }
        return this;
    }

    /**
     * 设置返回按钮的状态
     */
    public TitleLayout setTitleMenuText(String text) {
        Text component = createTitleMenu(ComponentType.Text);
        if (component != null) {
            component.setText(text);
        }
        return this;
    }

    public TitleLayout setTitleMenuTextColor(Color color) {
        Text component = createTitleMenu(ComponentType.Text);
        if (component != null) {
            component.setTextColor(color);
        }
        return this;
    }

    public TitleLayout setTitleMenuTextSize(int size) {
        Text component = createTitleMenu(ComponentType.Text);
        if (component != null) {
            component.setTextSize(size, Text.TextSizeType.FP);
        }
        return this;
    }

    /**
     * 设置右侧的 图片图标(与右侧的文本设置互斥)
     *
     * @param resId 资源路径
     */
    public TitleLayout setTitleMenuImage(int resId) {
        Image component = createTitleMenu(ComponentType.Image);
        if (component != null) {
            component.setPixelMap(resId);
        }
        return this;
    }

    /**
     * 动态创建 组件
     *
     * @param type {@link ComponentType}
     */
    private <T extends Component> T createTitleMenu(ComponentType type) {
        Component component = null;
        if (defaultRightLayout != null) {
            if (defaultRightLayout.getVisibility() != VISIBLE) {
                defaultRightLayout.setVisibility(VISIBLE);
            }
            if (defaultRightLayout.getChildCount() == 0) {
                if (type == null || type == ComponentType.Text) {
                    component = new Text(getContext());
                    ((Text) component).setTextAlignment(72);
                } else if (type == ComponentType.Image) {
                    component = new Image(getContext());
                }
                DependentLayout.LayoutConfig config = new DependentLayout.LayoutConfig();
                config.height = DependentLayout.LayoutConfig.MATCH_CONTENT;
                config.width = DependentLayout.LayoutConfig.MATCH_CONTENT;
                config.addRule(DependentLayout.LayoutConfig.CENTER_IN_PARENT);
                defaultRightLayout.addComponent(component, config);
                LogUtils.d("count ------->0");
            } else if (defaultRightLayout.getChildCount() > 1) {
                LogUtils.d("count -------> %s" + defaultRightLayout.getChildCount());
                component = defaultRightLayout.getComponentAt(0);
                for (int i = 1; i < defaultRightLayout.getChildCount(); i++) {
                    defaultRightLayout.removeComponentAt(i);
                }
//                defaultRightLayout.removeComponents(1, defaultRightLayout.getChildCount());
            } else {
                component = defaultRightLayout.getComponentAt(0);
                if ((type == null || type == ComponentType.Text) && !(component instanceof Text)) {
                    defaultRightLayout.removeComponent(component);
                    component = new Text(getContext());

                    DependentLayout.LayoutConfig config = new DependentLayout.LayoutConfig();
                    config.height = DependentLayout.LayoutConfig.MATCH_CONTENT;
                    config.width = DependentLayout.LayoutConfig.MATCH_CONTENT;
                    config.addRule(DependentLayout.LayoutConfig.CENTER_IN_PARENT);
                    defaultRightLayout.addComponent(component, config);
                } else if ((type == null || type == ComponentType.Image) && !(component instanceof Image)) {
                    defaultRightLayout.removeComponent(component);
                    component = new Image(getContext());

                    DependentLayout.LayoutConfig config = new DependentLayout.LayoutConfig();
                    config.height = DependentLayout.LayoutConfig.MATCH_CONTENT;
                    config.width = DependentLayout.LayoutConfig.MATCH_CONTENT;
                    config.addRule(DependentLayout.LayoutConfig.CENTER_IN_PARENT);
                    defaultRightLayout.addComponent(component, config);
                }

            }
            return (T) component;
        }
        return null;
    }

    /**
     * 设置返回监听
     */
    public TitleLayout setOnCallbackListener(Component.ClickedListener listener) {
        if (backLayout != null && backLayout.getVisibility() == VISIBLE) {
            backLayout.setClickedListener(listener);
        }
        return this;
    }

    /**
     * 自定义布局文件
     */
    public TitleLayout setCustomComponent(Component component) {
        if (customRightLayout == null) {
            LogUtils.w("自定义标题父组件不能为空");
            return this;
        }
        if (defaultLayout != null) {
            defaultLayout.setVisibility(HIDE);
        }
        if (customRightLayout.getVisibility() != VISIBLE) {
            customRightLayout.setVisibility(VISIBLE);
        }
        if (customRightLayout.getChildCount() > 0) {
            customRightLayout.removeAllComponents();
        }
        customRightLayout.addComponent(component);
        return this;
    }

    /**
     * 修改父组件属性
     */
    public TitleLayout setTitleLayoutConfig(ComponentContainer.LayoutConfig layoutConfig) {
        if (titleParent == null) {
            throw new IllegalArgumentException("父组件不能为空");
        }
        titleParent.setLayoutConfig(layoutConfig);
        return this;
    }


    /**
     * 根据 Id 获取相应的组件
     */
    public <T extends Component> T findComponentFromId(int id) {
        return (T) findComponentById(id);
    }

    //控件类型
    enum ComponentType {
        Text,
        Image
    }

}
